package com.itheima.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Category;
import com.itheima.common.ParamPage;
import com.itheima.common.R;
import com.itheima.exception.CustomException;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService cs;

    @GetMapping("/page")
    public R page(ParamPage page){
        Page<Category> page1 = cs.findPage(page);
        return R.success(page1);
    }
    @PostMapping
    public R add(@RequestBody Category category){
        if (cs.add(category)>0){
            return R.success("添加成功！");
        }else {
            return R.error("添加失败！");
        }
    }
    @PutMapping
    public R update(@RequestBody Category category){
        if (cs.update(category)>0){
            return R.success("修改成功！");
        }else {
            return R.error("修改失败！");
        }
    }
    @DeleteMapping("/{id}")
    public R delete(@PathVariable long id){
        int i = cs.delete(id);
        if (i==0){
            throw new CustomException("删除分类失败！");
        }
        if (i==-1){
            throw new CustomException("该菜品分类关联了菜品，不能删除，删除失败！");
        }
        if(i==-2){
            throw new CustomException("该套餐分类关联了套餐，不能删除，删除失败！");
        }
        return R.success("删除分类成功！");
    }
    @GetMapping("/list")
    public R list(Integer type){
        return R.success(cs.findByType(type));
    }
}
